package mqtt

import (
	"encoding/json"
	"strings"
	"time"

	"gitee.com/sansaniot/ssiot-core/logger"
	mqtt "github.com/eclipse/paho.mqtt.golang"

	"ssdevice/common/enums"
	"ssdevice/internal/data/partition"
)

var execRuleTask func(sensor map[string]interface{}, sn string, msgType string) map[string]interface{}

func RegisterRuleTask(ruleTask func(sensor map[string]interface{}, sn string, msgType string) map[string]interface{}) {
	execRuleTask = ruleTask
}

var n uint64

// 消息订阅处理
func TopicHandler(c mqtt.Client, message mqtt.Message) {
	if strings.HasSuffix(message.Topic(), "/ack") {
		return
	}
	//logger.Debugf("订阅到主题%s, 消息%s", message.Topic(), string(message.Payload()))
	n++
	if n%1000 == 0 {
		println("第", n, "条主题消息", time.Now().UnixMilli())
	}
	//获取业务大类
	typeValue := getPartialType(message.Topic())
	if len(typeValue) == 0 {
		return
	}
	// 获取处理对象
	bp := partition.GetPartialServe(typeValue)
	//判断是否有效
	if bp == nil {
		return
	}
	var jsonData map[string]interface{}
	if err := json.Unmarshal(message.Payload(), &jsonData); err != nil {
		// 登出可以无内容,非登出必需为json
		if typeValue != enums.Logout.Get().Name {
			logger.Error(err)
			return
		}
	}
	bp.Execute(message.Topic(), jsonData)
}

// 数据统一入口 (规则引擎、场景联动、入库)
// @param devDoc   数据input
// @param consumer 回调业务流程
func DealData(devSn string, devDoc map[string]interface{}, consumer func(map[string]interface{}), msgType enums.MsgType) {
	// 规则引擎
	go func() {
		if msgType == enums.SensorMsg && execRuleTask != nil {
			devDoc = execRuleTask(devDoc, devSn, enums.SensorMsg.Get().Name)
		}
		consumer(devDoc)
	}()
	//// TODO 场景联动
	//go func() {
	//
	//}()
}

// 获取业务大类
func getPartialType(topic string) string {
	split := strings.Split(topic, "/")
	if len(split) < 5 {
		return ""
	}
	//主题对应的业务类型
	typeValue := split[4]
	//选择有效注册业务
	active := false
	for _, bizItem := range enums.GetAllBizType() {
		if bizItem.Name == typeValue {
			active = true
		}
	}
	if active {
		return typeValue
	} else {
		return ""
	}
}
